package com.garmin.tw.garminpcsync.android;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.widget.ImageView;

public class AsyncImageView extends ImageView {

	public AsyncImageView(Context context) {
		super(context);
	}
	
	public AsyncImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public synchronized void loadImage(String imageURL){
		
		if (this.getDrawable() instanceof AnimationDrawable) {
			final AnimationDrawable loading = (AnimationDrawable)this.getDrawable();
	        
	        // image may be large so build it in a new thread
			MyAnimationRoutine mAnimationRoutine = new MyAnimationRoutine(loading);
			Timer timer = new Timer(false);
			timer.schedule(mAnimationRoutine, 0);
		}
		
		class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
			String url = "";

			@Override
			protected Bitmap doInBackground(String... args) {
				this.url = args[0];
				Bitmap bmp = this.download_Image(this.url);
				return bmp;
			}

			@Override
			protected void onPostExecute(Bitmap result) {
				super.onPostExecute(result);
				setImageBitmap(result);
			}
			
			private Bitmap download_Image(String url) {
			   
			    Bitmap bm = null;
			    try {
			        URL aURL = new URL(url);
			        URLConnection conn = aURL.openConnection();
			        conn.connect();
			        InputStream is = conn.getInputStream();
			        BufferedInputStream bis = new BufferedInputStream(is);
			        bm = BitmapFactory.decodeStream(bis);
			        bis.close();
			        is.close();
			    } catch (IOException e) {
			        //Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
			    } 
			    return bm;
			}
		}
		
		new DownloadImageTask().execute(imageURL);
	}
	
}

class MyAnimationRoutine extends TimerTask {

	private AnimationDrawable animationDrawable;
	
	public MyAnimationRoutine (AnimationDrawable _animationDrawable) {
		this.animationDrawable = _animationDrawable;
	}
	
	@Override
	public void run() {
		// if using animated loading image
		// start animation for the initial loading image
		try {
			this.animationDrawable.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
